<template>
  <div class="personal-info">
    <el-card class="info-card" v-if="isEditing">
      <h2 class="info-title">修改基本信息</h2>
      <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <!-- 姓名 -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <!-- 单位 -->
        <el-form-item label="单位" prop="university">
          <el-input v-model="formData.university" placeholder="请输入单位"></el-input>
        </el-form-item>

        <!-- 院系 -->
        <el-form-item label="院系" prop="depart">
          <el-input v-model="formData.depart" placeholder="请输入院系"></el-input>
        </el-form-item>

        <!-- 职称 -->
        <el-form-item label="职称" prop="academic">
          <el-select v-model="formData.academic" placeholder="请选择职称">
            <el-option label="教授" value="1"></el-option>
            <el-option label="副教授" value="2"></el-option>
            <el-option label="讲师" value="3"></el-option>
            <el-option label="本科生" value="4"></el-option>
            <el-option label="研究生" value="5"></el-option>
            <el-option label="其他人员" value="6"></el-option>
          </el-select>
        </el-form-item>

        <!-- 学工号 -->
        <el-form-item label="学工号" prop="uno">
          <el-input v-model="formData.uno" placeholder="请输入学工号"></el-input>
        </el-form-item>

        <!-- 电话 -->
        <el-form-item label="电话" prop="tel">
          <el-input v-model="formData.tel" placeholder="请输入电话"></el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="formData.mail" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="onSubmit">保存</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 基本信息 -->
    <el-card class="info-card" v-else>
      <h1 class="info-title">基本信息</h1>
      <div v-if="userInfo" class="profile-details">
        <div class="profile-item">
          <label>用户名：</label>
          <span>{{ userInfo.username }}</span>
        </div>

        <!-- 密码 -->
        <div class="profile-item">
          <label class="profile-label">密码：</label>
          <span class="profile-value">******</span>
          <el-button type="text" class="edit-button" @click="openPasswordDialog">修改</el-button>
        </div>

        <div class="profile-item">
          <label>姓名：</label>
          <span>{{ userInfo.name }}</span>
        </div>
        <div class="profile-item">
          <label>单位：</label>
          <span>{{ userInfo.university }}</span>
        </div>
        <div class="profile-item">
          <label>院系：</label>
          <span>{{ userInfo.depart }}</span>
        </div>
        <div class="profile-item">
          <label>职称：</label>
          <span>{{ getAcademicLabel(userInfo.academic) }}</span>
        </div>
        <div class="profile-item">
          <label>学工号：</label>
          <span>{{ userInfo.uno }}</span>
        </div>
        <div class="profile-item">
          <label>电话：</label>
          <span>{{ userInfo.tel }}</span>
        </div>
        <div class="profile-item">
          <label>邮箱：</label>
          <span>{{ userInfo.mail }}</span>
        </div>
      </div>
      <el-button type="primary" v-if="userInfo" @click="goToEditPage">修改基本信息</el-button>
    </el-card>

    <!-- 修改密码弹窗 -->
    <el-dialog title="修改密码" v-model="showPasswordDialog" width="500px">
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="passwordForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input type="password" v-model="passwordForm.oldPassword" placeholder="请输入当前密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="passwordForm.newPassword" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPassword">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "PersonalInfo",
  data() {
    return {
      formData: {
        id: null, // 用户ID
        username: "",
        name: "",
        university: "",
        depart: "",
        academic: "",
        uno: "",
        tel: "",
        mail: "",
      },
      userInfo: null, // 用于存储后端返回的用户信息
      isEditing: false, // 是否处于编辑状态
      showPasswordDialog: false, // 控制修改密码弹窗的显示
      passwordForm: {
        username: "",
        oldPassword: "",
        newPassword: "",
      },
      passwordRules: {
        oldPassword: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
        newPassword: [{ required: true, message: "请输入新密码", trigger: "blur" }],
      },
      loading: false, // 保存按钮的加载状态
      rules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        university: [{ required: true, message: "请输入单位", trigger: "blur" }],
        depart: [{ required: true, message: "请输入院系", trigger: "blur" }],
        academic: [{ required: true, message: "请选择职称", trigger: "change" }],
        uno: [{ required: true, message: "请输入学工号", trigger: "blur" }],
        tel: [{ required: true, message: "请输入电话", trigger: "blur" }],
        mail: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
      },
    };
  },
  created() {
    this.fetchUserInfo();
  },

  methods: {
    // 从后端获取用户信息，将后端返回的数据存储到 userInfo和passwordForm.username中，以便在前端页面中显示或使用这些信息
    async fetchUserInfo() {
      try {
        const token = localStorage.getItem("token"); // 从浏览器的本地存储中获取token,token 用于认证
        const userId = localStorage.getItem("id"); // 从本地存储中获取当前userId,userId 用于识别用户。
        const url = `/api/User/getUserById?id=${userId}`; // 使用用户 ID 动态生成后端接口的完整路径，例如：api/User/getUserById?id=123
        const response = await fetch(url, {
          headers: { Authorization: `Bearer ${token}` },
        }); // 在请求头中添加 Authorization，后端将根据 token 验证用户权限并返回用户信息
        const data = await response.json(); // 将后端返回的响应数据转换为 JSON 格式，并存储到 data 变量中
        if (data.code === "200") {
          this.userInfo = data.data; // 将后端返回的用户信息存储到组件的 userInfo 属性中
          this.passwordForm.username = data.data.username; // passwordForm.username 用于修改密码的表单中显示用户名。
        } else {
          throw new Error(data.message || "无法获取用户信息"); // 如果状态码不是 200，则抛出一个错误。
        }
      } catch (error) {
        console.error("获取用户信息失败:", error); // 捕获所有潜在的异常，并记录到控制台以便排查问题
      }
    },
    // 提交用户修改后的个人信息,将用户修改后的个人信息提交给后端接口 api/User/updateUser
    async onSubmit() {
      try {
        this.loading = true;
        const token = localStorage.getItem("token");
        const url = `/api/User/updateUser`;

        const response = await fetch(url, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify(this.formData),
        });

        const data = await response.json();
        if (data.code === "200") {
          this.userInfo = data.data;
          this.isEditing = false;
          this.$message.success("修改成功！");
        } else {
          throw new Error(data.message || "修改失败");
        }
      } catch (error) {
        console.error("提交失败:", error.message);
        this.$message.error("提交失败，请稍后再试！");
      } finally {
        this.loading = false;
      }
    },
    // 提交用户输入的密码修改请求，并根据后端返回的结果显示提示信息或关闭弹窗
    async submitPassword() {
      try {
        if (!this.passwordForm.username || !this.passwordForm.oldPassword || !this.passwordForm.newPassword) {
          this.$message.error("请填写完整的表单信息！");
          return;
        }

        // 使用 URLSearchParams 传递表单数据
        const formData = new URLSearchParams();
        formData.append("username", this.passwordForm.username);
        formData.append("oldPassword", this.passwordForm.oldPassword);
        formData.append("newPassword", this.passwordForm.newPassword);

        const response = await fetch("/api/api/password/password", {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: formData.toString(),
        });

        const data = await response.json();
        if (data.code === "200") {
          this.$message.success("密码修改成功！");
          this.showPasswordDialog = false;
          this.passwordForm.oldPassword = "";
          this.passwordForm.newPassword = "";
        } else {
          this.$message.error(data.message || "密码修改失败！");
        }
      } catch (error) {
        console.error("请求失败：", error);
        this.$message.error("请求失败，请稍后重试！");
      }
    },

    // 当用户“取消"修改个人信息时，退出编辑模式，进入基本信息页面
    onCancel() {
      this.isEditing = false;
    },
    // 当用户点击“修改个人信息”按钮时调用，进入编辑模式
    goToEditPage() {
      this.isEditing = true;
      this.formData = { ...this.userInfo };
    },
    // 当用户点击“修改密码”按钮时调用
    openPasswordDialog() {
      this.passwordForm.oldPassword = "";
      this.passwordForm.newPassword = "";
      this.showPasswordDialog = true;
    },
    // 在基本信息页面中显示用户职称的中文名称，而不是直接显示编号
    getAcademicLabel(value) {
      const academicMap = {
        "1": "教授",
        "2": "副教授",
        "3": "讲师",
        "4": "本科生",
        "5": "研究生",
        "6": "其他人员",
      };
      return academicMap[value] || "未知";
    },
  },
};
</script>

<style scoped>

.personal-info {
  max-width: 900px;
  margin: 0 auto;
  text-align: left;
}

.info-card {
  padding: 20px;
  margin: 0 auto;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.profile-details .profile-item {
  margin-bottom: 15px;
}

.profile-label {
  width: 50px;
  display: inline-block;
}

.info-title {
  font-weight: bold; /* 加粗文字 */
  font-size: 28px; /* 可选，调整字体大小 */
  margin-bottom: 30px; /* 增加底部间距 */
}

</style>
